package com.aabte.permissionframeworklearn.permission.util;

import com.aabte.permissionframeworklearn.permission.beans.Mail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

import java.util.List;

/**
 * @author Daniel
 */
@Slf4j
public class MailUtil {

    private final static String MAIL_SERVER_HOST = "smtp.163.com";
    private final static String MAIL_SENDER_ADDRESS = "15515664xxx@163.com";
    private final static String MAIL_SENDER_NICK = "敲代码的卡卡罗特";
    private final static String MAIL_SENDER_USERNAME = "15515664xxx@163.com";
    private final static String MAIL_SENDER_PASSWORD = "xxxxx";

    public static boolean send(Mail mail) {
        log.info("Start send mail. mail: {}", mail);
        try {
            HtmlEmail email = new HtmlEmail();
            // 配置信息
            email.setHostName(MAIL_SERVER_HOST);
            email.setFrom(MAIL_SENDER_ADDRESS, MAIL_SENDER_NICK);
            email.setAuthentication(MAIL_SENDER_USERNAME, MAIL_SENDER_PASSWORD);
            email.setCharset("UTF-8");
            email.setSubject(mail.getSubject());
            email.setHtmlMsg(mail.getContent());

            // 添加附件
            List<EmailAttachment> attachments = mail.getAttachments();
            if (null != attachments && attachments.size() > 0) {
                for (int i = 0; i < attachments.size(); i++) {
                    email.attach(attachments.get(i));
                }
            }

            // 收件人
            List<String> toAddress = mail.getToAddress();
            if (null != toAddress && toAddress.size() > 0) {
                for (int i = 0; i < toAddress.size(); i++) {
                    email.addTo(toAddress.get(i));
                }
            }
            // 抄送人
            List<String> ccAddress = mail.getCcAddress();
            if (null != ccAddress && ccAddress.size() > 0) {
                for (String address : ccAddress) {
                    email.addCc(address);
                }
            }
            //邮件模板 密送人
            List<String> bccAddress = mail.getBccAddress();
            if (null != bccAddress && bccAddress.size() > 0) {
                for (String address : bccAddress) {
                    email.addBcc(address);
                }
            }
            email.send();
            log.info("Send mail success.");
            return true;
        } catch (EmailException e) {
            log.error("Send mail error. mail: {}, ex: ", mail, e);
            return false;
        }
    }

}
